package com.cf.conf.core;

import com.cf.constant.EnumReturnCode;
import com.cf.exception.BizException;
import com.cf.util.ReflectionUtil;
import com.cf.util.SpringBeanUtil;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessorAdapter;

import java.lang.reflect.Field;
import java.util.List;

/**
 * springboot-thymeleaf-ConfigInstantiationAwareBeanPostprocessor
 *
 * @author <a href="2428922347@qq.com">Zhu mingming</a>
 * @info
 * @since 2018/6/8 下午 01:25
 */
public class ConfigSetAndUpdateBeanPostprocessor extends InstantiationAwareBeanPostProcessorAdapter {

    @Autowired
    private PropertyManager propertyManager;

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        List<Field> fields = ReflectionUtil.getFields(bean.getClass());

        for (Field field : fields) {
            ZValue annotation = field.getAnnotation(ZValue.class);
            if (annotation != null) {
                try {
                    propertyManager.registerField(annotation.key(), bean, field);
                } catch (Exception e) {
                    throw new BizException(EnumReturnCode.ERROR.getCode(), "属性设置异常", e);
                }
            }
        }

        return super.postProcessAfterInitialization(bean, beanName);
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return super.postProcessBeforeInitialization(bean, beanName);
    }

}
